package org.jeecg.modules.ws.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.ws.entity.WsHblxDetail;
import org.jeecg.modules.ws.entity.WsHbfxInterest;
import org.jeecg.modules.ws.service.IWsHbfxInterestService;
import org.jeecg.modules.ws.service.IWsHblxDetailService;
import org.jeecg.modules.ws.service.IWsHblxInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 还本利息
 *
 * @author ZJJ
 * @date 2025-04-03 上午11:36
 * @copyright Copyright (c) 2025 ZJJ
 */
@Slf4j
@Component
public class HblxJob {
    @Autowired
    private IWsHblxInfoService wsHblxInfoService;
    @Autowired
    private IWsHblxDetailService wsHblxDetailService;
    @Autowired
    private IWsHbfxInterestService wsHbfxInterestService;

    /**
     * 计算利息
     * 每天凌晨1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void computeInterest() {
        try {
            // 获取所有债券详情
            List<WsHblxDetail> details = wsHblxDetailService.list();
            
            for (WsHblxDetail detail : details) {
                // 获取发行日期
                Date fxrq = detail.getFxrq();
                if (fxrq == null) {
                    continue;
                }

                // 解析年限
                String nx = detail.getNx();
                int yearLimit;
                try {
                    yearLimit = Integer.parseInt(nx);
                } catch (NumberFormatException e) {
                    log.error("债券[{}]年限格式错误: {}", detail.getBondCode(), nx);
                    continue;
                }

                // 获取当前时间
                Calendar now = Calendar.getInstance();
                
                // 获取发行日期的日历对象
                Calendar fxrqCal = Calendar.getInstance();
                fxrqCal.setTime(fxrq);
                
                // 如果不是每月1号，跳过
                if (now.get(Calendar.DAY_OF_MONTH) != 1) {
                    return;
                }

                // 计算发行至今的月数
                int months = (now.get(Calendar.YEAR) - fxrqCal.get(Calendar.YEAR)) * 12 
                            + now.get(Calendar.MONTH) - fxrqCal.get(Calendar.MONTH);

                // 10年以上债券，每半年计息
                if (yearLimit >= 10) {
                    // 第一次计息需要在发行6个月后
                    if (months < 6) {
                        continue;
                    }
                    // 每6个月计息一次
                    if ((months - 6) % 6 != 0) {
                        continue;
                    }
                    
                    // 计算半年利息
                    BigDecimal interest = detail.getBj().multiply(detail.getLl()).divide(new BigDecimal("2"), 2, BigDecimal.ROUND_HALF_UP);
                    saveInterest(detail, interest, String.valueOf(now.get(Calendar.YEAR)));
                }
                // 10年以下债券，每年计息
                else {
                    // 第一次计息需要在发行12个月后
                    if (months < 12) {
                        continue;
                    }
                    // 每12个月计息一次
                    if ((months - 12) % 12 != 0) {
                        continue;
                    }
                    
                    // 计算年利息
                    BigDecimal interest = detail.getBj().multiply(detail.getLl());
                    saveInterest(detail, interest, String.valueOf(now.get(Calendar.YEAR)));
                }
            }
            
            log.info("计算利息任务执行完成");
        } catch (Exception e) {
            log.error("计算利息失败", e);
        }
    }

    /**
     * 保存利息记录
     */
    private void saveInterest(WsHblxDetail detail, BigDecimal interest, String year) {
        // 检查是否已经存在该年份的记录
        LambdaQueryWrapper<WsHbfxInterest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WsHbfxInterest::getBondCode, detail.getBondCode())
               .eq(WsHbfxInterest::getYear, year);
        
        if (wsHbfxInterestService.count(wrapper) > 0) {
            return;
        }

        // 创建新的付息记录
        WsHbfxInterest wsHbfxInterest = new WsHbfxInterest();
        wsHbfxInterest.setBondCode(detail.getBondCode());
        wsHbfxInterest.setProjectCode(detail.getProjectCode());
        wsHbfxInterest.setYear(year);
        wsHbfxInterest.setInterest(interest);
        wsHbfxInterest.setCreateTime(new Date());
        wsHbfxInterest.setUpdateTime(new Date());
        
        wsHbfxInterestService.save(wsHbfxInterest);
    }
}
